package ar.edu.uba.fi.jmit.monitorengine.backend.server.mock;
import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;

/**
 * Esta clase es la que se encarga de recibir los request
 * cuando se sube un archivo, y guardarlo donde corresponda.
 * @author Cristian
 *
 */
public class UploadServletMock extends UploadAction {

	private static final long serialVersionUID = -4648428590575138957L;

	@Override
	public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
		String response = "";
		int cont = 0;
		for (FileItem item : sessionFiles) {
			if (false == item.isFormField()) {
				cont++;
				try {
					response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n";
					response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n";
					response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n";
					response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n";
				} catch (Exception e) {
					throw new UploadActionException(e);
				}
			}
		}

		removeSessionFileItems(request);

		return "<response>\n" + response + "</response>\n";
	}

	//  /**
	//   * Get the content of an uploaded file.
	//   */
	//  @Override
	//  public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
	//	  log("getUploadedFile");
	//	  GWT.log("getUploadedFile");
	//    String fieldName = request.getParameter(PARAM_SHOW);
	//    File f = receivedFiles.get(fieldName);
	//    if (f != null) {
	//      response.setContentType(receivedContentTypes.get(fieldName));
	//      FileInputStream is = new FileInputStream(f);
	//      copyFromInputStreamToOutputStream(is, response.getOutputStream());
	//    } else {
	//      renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
	//   }
	//  }
	//  
	//  /**
	//   * Remove a file when the user sends a delete request.
	//   */
	//  @Override
	//  public void removeItem(HttpServletRequest request, String fieldName)  throws UploadActionException {
	//	  log("removeItem");
	//	  GWT.log("removeItem");
	//    File file = receivedFiles.get(fieldName);
	//    receivedFiles.remove(fieldName);
	//    receivedContentTypes.remove(fieldName);
	//    if (file != null) {
	//      file.delete();
	//    }
	//  }

}